package sectorCrack.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class DataReader {
	private static int WORD_SIZE = 4; // byte

	File file;

	public static long getUnsignedInt(int fourByte) {
		ByteBuffer bb = ByteBuffer.allocate(8);
		bb.putInt(0);
		bb.putInt(fourByte);
		return bb.getLong(0);
	}

	public static int[] get2ShortFromInt(int fourByte) {
		int[] temp = new int[2];
		int[] result = new int[2];
		ByteBuffer bb = ByteBuffer.allocate(4);
		bb.putInt(fourByte);
		temp[0] = bb.getShort(0);
		temp[1] = bb.getShort(2);
		int i = 0;
		for (int s : temp) {
			ByteBuffer bb2 = ByteBuffer.allocate(4);
			bb2.putShort((short) 0);
			bb2.putShort((short) s);
			result[i] = bb2.getInt(0);
			i++;
		}
		return result;
	}

	public DataReader(String filename) {
		this.file = new File(filename);

	}

	public String toHexString(int num) {
		String result = Integer.toHexString(num);
		for (int i = result.length(); i < 8; i++) {
			result = "0" + result;
		}
		return result;
	}

	public void read() throws IOException {
		System.out.println("started reading");
		FileInputStream fis = new FileInputStream(file);
		byte[] arr = new byte[WORD_SIZE];
		while (fis.read(arr) != -1) {
			ByteBuffer bb = ByteBuffer.wrap(arr);
			while (bb.hasRemaining()) {
				// bb.order(ByteOrder.LITTLE_ENDIAN);

				int temp = (int) bb.getInt();

				long readInt = getUnsignedInt(temp);

				if (readInt == 1148) {
					System.out.println("start of system status message");
				} else if (readInt == 1111) {
					System.out.println("start of microburst product message");

				} else {
					int[] tail = get2ShortFromInt(temp);
					System.out.println(toHexString(temp) + "\t" + tail[0] + "\t" + tail[1] + "\t" + readInt + "\t" + temp + " ");
				}
			}
		}

		fis.close();
	}

}
